package com.wbt.bambootown.ui.view.recyclerview;

import android.content.Context;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhang on 2016/9/1.
 */
public abstract class BaseAdapter<M, VH extends BaseViewHolder> extends AbsAdapter<VH> {

    private List<M> dataList;

    public BaseAdapter(Context context) {
        super(context);
        dataList = new ArrayList<>();
    }

    public BaseAdapter(Context context, List<M> dataList) {
        this(context);
        this.dataList.addAll(dataList);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return dataList.size() + getExtraCount();
    }

    @Override
    public final int getItemViewType(int position) {
        if (headerView != null && position == 0) {
            return VIEW_TYPE_HEADER;
        } else if (footerView != null && position == dataList.size() + getHeaderCount()) {
            return VIEW_TYPE_FOOTER;
        } else {
            return getCustomViewType(position);
        }
    }

    /**
     * 获取自定义View的类型
     *
     * @param position 位置
     * @return View的类型
     */
    public abstract int getCustomViewType(int position);

    public void setList(List<M> dataList) {
        this.dataList.clear();
        this.dataList.addAll(dataList);
        notifyDataSetChanged();
    }

    public void appendItem(M data) {
        this.dataList.add(data);
        notifyItemInserted(dataList.size() - (1 - getHeaderCount()));
    }

    public void appendList(List<M> dataList) {
        this.dataList.addAll(dataList);
        notifyDataSetChanged();
    }

    public void proposeItem(M data) {
        this.dataList.add(0, data);
        notifyItemInserted(getHeaderCount());
    }

    public void proposeList(List<M> dataList) {
        this.dataList.addAll(0, dataList);
        notifyDataSetChanged();
    }

    public M getItem(int position) {
        if (position < getHeaderCount() || position >= dataList.size() + getHeaderCount()) {
            return null;
        }
        return dataList.get(position - getHeaderCount());
    }

    public void updateItem(M data) {
        int index = dataList.indexOf(data);
        if (index < 0) {
            return;
        }
        dataList.set(index, data);
        notifyItemChanged(index + getHeaderCount());
    }

    /**
     * 移除一条数据
     *
     * @param position 位置
     */
    public void removeItem(int position) {
        dataList.remove(position - getHeaderCount());
        notifyItemRemoved(position);
    }

    public void removeAll(){
        dataList.clear();
        notifyDataSetChanged();
    }

    /**
     * 移除一条数据
     *
     * @param data 要移除的数据
     */
    public void removeItem(M data) {
        int index = dataList.indexOf(data);
        if (index < 0) {
            return;
        }
        dataList.remove(index);
        notifyItemRemoved(index + getHeaderCount());
    }
}
